#include <iostream>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX 1024

using namespace std;

int main()
{
    // 第一步，建立管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n == 0); // 只有在debug模式下才存在的
    //(void *)n;      // 防止编译器告警

    cout << "pipefd[0]: " << pipefd[0] << ",pipefd[1]: " << pipefd[1] << endl;

    // 第二步，创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        perror("fork");
        return 1;
    }

    //第三步，父子各自关闭不需要的fd，形成单向通信的管道
    //子写，父读
    if (id == 0)
    {
        // child
        close(pipefd[0]);
        //w
        int cnt = 10;
        while(1)
        {
            // char c = 'a';
            // write(pipefd[1], &c, 1);
            // cnt++;
            // cout << "write..." << cnt << endl;

            char message[MAX];
            snprintf(message, sizeof(message), "hello father, I am child, pid: %d, cnt: %d", getpid(), cnt);
            cnt--;
            write(pipefd[1], message, strlen(message));
            sleep(1);
            cout << "write..." << cnt << endl;
        }

        exit(0);
    }
    // father
    close(pipefd[1]);
    char buffer[MAX];
    while(1)
    {
        //sleep(200);
        ssize_t n = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;// 相当于'\0';
            cout << getpid() << "child say:" << buffer << "to me!" << endl;
        }
        else if(n == 0)
        {
            cout << "child quit, me too !" << endl;
            break;
        }
        sleep(1);
        break;  
    }

    close(pipefd[0]);
    sleep(5);
    int status = 0;

    pid_t rid = waitpid(id, &status, 0);
    if(rid == id)
    {
        cout << "wait success, child exit sig:" << (status&0x7F) << endl;
    }
    return 0;
}